package com.jz.community.basecomm.loaction;

import android.content.Context;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.jz.community.basecomm.bean.LocationFromAmap;


public class LocationManager implements AMapLocationListener {
    private GetLocationListener mGetProductListener;

    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;

    public static class GetLocationResult {
        public int mResultId;
        public String mResultMsg;
        public LocationFromAmap mLocation;

        public GetLocationResult(int resultId, String msg, LocationFromAmap location) {
            mResultId = resultId;
            mResultMsg = msg;
            mLocation = location;
        }
    }

    public interface GetLocationListener {
        void OnResult(GetLocationResult result);
    }

    public void getLocation(GetLocationListener listener, Context context) {
        mGetProductListener = listener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(context);
            mLocationOption = new AMapLocationClientOption();
            mLocationOption.setOnceLocation(true);
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            mlocationClient.startLocation();
        }
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            double latitude = aMapLocation.getLatitude();
            double longitude = aMapLocation.getLongitude();
            String province = aMapLocation.getProvince();
            String city = aMapLocation.getCity();
            String code = aMapLocation.getCityCode();
            LocationFromAmap l = new LocationFromAmap(latitude, longitude, province, city, code);
            l.mResultCode = aMapLocation.getErrorCode();
            if (l.mResultCode == 0) {
                mGetProductListener.OnResult(new GetLocationResult(0, "", l));
            } else {
                mGetProductListener.OnResult(new GetLocationResult(-1, "", null));
            }
        } else {
            mGetProductListener.OnResult(new GetLocationResult(-1, "", null));
        }
    }

    public void stopLocation() {
        if (null != mlocationClient) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
    }

}
